/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;
import java.sql.*;
import javax.swing.JOptionPane;

/**
 *
 * @author mrossetti
 */
public class DbConnection {
    
    private Connection C;
    ResultSet rs;
    Statement S;
    private static String ConnString = "jdbc:mysql://localhost:3306/thewarehouse";
    
    public DbConnection(){
        C = null;
        rs = null;
        S = null;
        initConnection();
    }
    
    public void initConnection(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            C = DriverManager.getConnection(ConnString, "warehouser", "warehouser");
            C.setAutoCommit(false);
        }catch(Exception e){
            e.printStackTrace();
            StackTraceElement[] message = e.getStackTrace();
            String err = "";
            for(int i=0;i<message.length;i++){
                err = err + message[i].toString() + "\n";
            }
            JOptionPane.showMessageDialog(null, err);
        }
    }
    
    public Connection getConnection(){
        return C;
    }
    
    public ResultSet getResultSet(String SQL){
        try{
            if(S != null)if(!S.isClosed())S.close();
            S = C.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = S.executeQuery(SQL);
            C.commit();
        }catch(Exception e){
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        return rs;
    }
    
    public boolean executeQuery(String SQL){
        boolean esito = false;
        try{
            PreparedStatement PS = C.prepareStatement(SQL);
            esito = PS.execute();
            esito = true;
            if(esito)C.commit();
            PS.close();
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        return esito;
    }
    
    public void CloseConnection(){
        try{
            if(rs != null)if(!rs.isClosed())rs.close();
            if(S != null)if(!S.isClosed())S.close();
            if(C != null)if(!C.isClosed())C.close();
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }
}
